//
//  JYChatVC.m
//  Pods
//
//  Created by JY on 2017/5/4.
//
//

#import "JYChatVC.h"
#import "JYChatCell.h"
#import "JYUser.h"
#import <AFNetworking/AFNetworking.h>

static NSString *const kErrorMsg = @"";
static NSString *const kResponseState = @"state";
static NSString *const kResponseStatus = @"code";
static NSString *const kResponseMessage = @"msg";
static NSString *const kResponseData = @"data";

typedef void(^NORequestSuccess)(id responseObject);
typedef void(^NORequestFailure)(NSString *error);

@interface JYChatVC ()

@property(strong,nonatomic) NSMutableArray *dataSource;
@property(strong,nonatomic) NSTimer *timer;
@property(weak,nonatomic) UILabel *label;

@end

@implementation JYChatVC

-(NSTimer *)timer{
    if (_timer == nil) {
        _timer = [NSTimer timerWithTimeInterval:3.0 target:self selector:@selector(requestData) userInfo:nil repeats:YES];
    }
    return _timer;
}

-(NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [NSMutableArray array];
    }
    return _dataSource;
}
    
- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.separatorStyle = NO;
    self.tableView.backgroundColor = [UIColor colorWithRed:243 / 255.0 green:244 / 255.0 blue:245 / 255.0 alpha:1.0];
    [self.tableView registerClass:[JYChatCell class] forCellReuseIdentifier:@"chat"];
    [self requestData];
    [[NSRunLoop currentRunLoop]addTimer:self.timer forMode:NSRunLoopCommonModes];
    UILabel *label = [[UILabel alloc]init];
    label.text = @"暂时没有可互撩的人哦";
    label.font =  [UIFont systemFontOfSize:15];
    CGFloat textW = [label.text sizeWithFont:[UIFont systemFontOfSize:15] constrainedToSize:CGSizeMake(CGFLOAT_MAX, CGFLOAT_MAX)].width;
    label.bounds = CGRectMake(0,0, textW, 23);
    label.center = CGPointMake(self.tableView.frame.size.width * 0.5, self.tableView.frame.size.height * 0.4);
    [self.view addSubview:label];
    self.label = label;
    self.label.hidden = YES;
}


-(void)requestData{
    [self getUsersuccess:^(NSDictionary  *responseObject) {
        NSLog(@"8888--%@",responseObject);
        [self.dataSource removeAllObjects];
        NSArray *arr = responseObject[@"dataList"];
        for (NSDictionary *dict in arr) {
            JYUser *user = [JYUser modelWithDict:dict];
            [self.dataSource addObject:user];
        }
        [self.tableView reloadData];
    } failure:^(NSString *error) {
        NSLog(@"9999--%@",error);
    }];
}


- (void)getUsersuccess:(NORequestSuccess)success
                    failure:(NORequestFailure)failure{
    NSUserDefaults *userInfo = [NSUserDefaults standardUserDefaults];
    NSString *uid = [userInfo objectForKey:@"uid"];
    NSDictionary *paraters = @{
                               @"uid":uid
                               };
    [[self class]networkRequestPOST:@"https://www.imonly.com/imonly-web/rel/friends" parameters:paraters success:success failure:failure];
}


+(void)networkRequestPOST:(NSString *)url
parameters:(NSDictionary *)parameters
success:(void(^)(id object))success
failure:(void(^)(id error))failure
{
//
//
//    // HTTPS Setting
//    NSString *cerPath = [[NSBundle mainBundle] pathForResource:@"https" ofType:@"cer"];
//    NSData * certData =[NSData dataWithContentsOfFile:cerPath];
//    NSSet * certSet = [[NSSet alloc] initWithObjects:certData, nil];
//    AFSecurityPolicy *securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
//    // 是否允许,NO-- 不允许无效的证书
//    [securityPolicy setAllowInvalidCertificates:YES];
//    // 设置证书
//    [securityPolicy setPinnedCertificates:certSet];
    
    // Request
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];

//设置requestSerializer



    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/plain", @"text/html", nil];
    
    [manager POST:url parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            // 先去除 null
            responseObject = WWJSONObjectResetNullValue(responseObject, NSJSONReadingAllowFragments);
            
            // 获得状态码
            NSDictionary *state = responseObject[kResponseState];
            NSInteger status = [state[kResponseStatus]integerValue];
            if(status == 0) {
                success(responseObject[kResponseData]);
            } else {
                failure(state[kResponseMessage]);
            }
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        failure(@"网络连接错误");
    }];
}

static id WWJSONObjectResetNullValue(id JSONObject, NSJSONReadingOptions readingOptions) {
    if ([JSONObject isKindOfClass:[NSArray class]]) {
        NSMutableArray *mutableArray = [NSMutableArray arrayWithCapacity:[(NSArray *)JSONObject count]];
        for (id value in (NSArray *)JSONObject) {
            [mutableArray addObject:WWJSONObjectResetNullValue(value, readingOptions)];
        }
        
        return (readingOptions & NSJSONReadingMutableContainers) ? mutableArray : [NSArray arrayWithArray:mutableArray];
    } else if ([JSONObject isKindOfClass:[NSDictionary class]]) {
        NSMutableDictionary *mutableDictionary = [NSMutableDictionary dictionaryWithDictionary:JSONObject];
        for (id <NSCopying> key in [(NSDictionary *)JSONObject allKeys]) {
            id value = (NSDictionary *)JSONObject[key];
            if (!value || [value isEqual:[NSNull null]]) {
                [mutableDictionary setObject:@"" forKey:key];
            } else if ([value isKindOfClass:[NSArray class]] || [value isKindOfClass:[NSDictionary class]]) {
                mutableDictionary[key] = WWJSONObjectResetNullValue(value, readingOptions);
            }
        }
        
        return (readingOptions & NSJSONReadingMutableContainers) ? mutableDictionary : [NSDictionary dictionaryWithDictionary:mutableDictionary];
    }
    
    return JSONObject;
}

#pragma mark - Table view data source


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.dataSource.count == 0) {
        self.label.hidden = NO;
    } else {
        self.label.hidden = YES;
    }
    return self.dataSource.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    JYChatCell *cell = [JYChatCell cellWithTableView:tableView];
    cell.user = self.dataSource[indexPath.row];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone]; 
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70;
}


@end
